<template>
  <div class="pro-table__body">
    <Card dis-hover>
<!--      <div :style="{fontSize: '14px',height: '40px', lineHeight: '40px', display: 'flex'}">-->
<!--        &lt;!&ndash; <span>共计</span> &ndash;&gt;-->
<!--        &lt;!&ndash; <span style="color:#337ab7">{{pageInfo.pagination.total}}</span> &ndash;&gt;-->
<!--        &lt;!&ndash; <span>条相关信息</span> &ndash;&gt;-->
<!--        <div :style="{flex: 1, textAlign: 'left',marginRight: '20px'}">-->
<!--          <Divider type="vertical"/>-->
<!--          <slot/>-->
<!--        </div>-->
<!--      </div>-->
      <template #extra>
        <slot name="extra"></slot>
      </template>

      <Table :maxHeight="isFixedHeader ? '600' : 'auto'" :columns="columnsData" :row-class-name="rowClassName"
             :data="pageInfo.list" border size="small" :loading="loading" @on-selection-change="handleSelectChange"
             @on-sort-change="handleSortChange" ref="tables"/>
      <div :style="{textAlign: 'right'}" v-if="showPageInfo" style="margin-top: 20px">
        <Page :total="pageInfo.pagination.total" :current="pageInfo.pagination.currentPage"
              :page-size="pageInfo.pagination.pageSize"
              show-total show-elevator show-sizer placement="top" @on-change="handlePageChange"
              @on-page-size-change="handlePageSizeChange"/>
      </div>
      <div v-if="showCount" class="show_count">总条数: 共{{ pageInfo.pagination.total }}条</div>
    </Card>
  </div>
</template>
<style lang="less">
</style>
<script>
import {
  Table,
  Page,
  Divider
} from "view-design";
import appService from "@/utils/appService";
import compare from "@/utils/compare";
import util from "@/utils/util"
import {namespace} from '../../views/trade/admin/tenantMenage/module/commercial';

export default {
  name: "RemoteTable",
  props: {
    /** vuex module名称 */
    namespace: String,
    /** 渲染列 */
    columns: Array,
    /** 是否显示分页 */
    showPageInfo: {
      type: Boolean,
      default: true
    },
    showCount: {
      type: Boolean,
      default: false
    },
    /** 是否需要参数才抓取数据 */
    needQueryParam: {
      type: Boolean,
      default: false,
      required: false
    },
    /** 查询参数 */
    queryParam: Object,
    /** 数据的唯一性key */
    primaryKey: {
      type: String,
      default: "id"
    },
    /** 选中项目 */
    selected: {
      type: Array,
      default: () => [],
      required: false
    },
    /** 是否清空store namespace模块中的query数据 */
    isClearStoreQuery: {
      type: Boolean,
      default: false
    },
    /** 是否固定表头，如果固定表头，会默认给 600 的高度**/
    isFixedHeader: {
      type: Boolean,
      default: false
    }
    // /** 表格行颜色标注 */
    // rowClassName: {
    //   type: String,
    //   default: null
    // }
  },
  model: {
    event: [
      "on-selection-change",
      "onSelectionChange",
      "onSelectCancel",
      "onSortChange"
    ]
  },
  components: {
    Table,
    Page,
    Divider
  },
  beforeMount() {
    this.loadData();
  },
  watch: {
    namespace: function (newValue, oldValue) {
      this.loadData();
    },
    queryParam: function (newValue, oldValue) {
      if (!compare(newValue, oldValue)) {
        this.loadData();
      }
    }
  },
  data: function () {
    return {
      /** 当前tables中存在且选中的行 */
      selectedRows: []
    };
  },
  computed: {
    pageInfo() {
      let namespace = this.$props.namespace;
      let pageInfo = this.$store.state[namespace].pageInfo;
      if (!pageInfo) {
        pageInfo = {};
      }
      if (!pageInfo.pagination) {
        pageInfo.pagination = {
          total: 0
        };
      }
      if (!pageInfo.list) {
        pageInfo.list = [];
      }
      let list = pageInfo.list;
      let selected = this.selected;
      let selectedRows = [];
      for (let i = 0; i < list.length; i++) {
        let row = list[i];
        let ex = false;
        for (let h = 0; h < selected.length; h++) {
          let cuSelected = selected[h];
          if (cuSelected instanceof Object) {
            if (row[this.primaryKey] == cuSelected[this.primaryKey]) {
              ex = true;
              break;
            }
          } else {
            if (row[this.primaryKey] == cuSelected) {
              ex = true;
              break;
            }
          }
        }
        if (ex) {
          row._checked = true;
          selectedRows.push(row);
        }
      }
      this.selectedRows = selectedRows;
      // pageInfo.pagination = {
      //   total: 100
      // };
      // pageInfo.list = [{
      //   email: '1131476232@qq.com',
      //   sn: '123546',
      //   name: '张三',
      //   num: '123546',
      //   legalPersonName: '张三',
      //   phone: '123546',
      //   cityName: '张三',
      //   status: '123546',
      //   createTime: '2024-02-29'
      // }];
      return pageInfo;
    },
    loading: function () {
      let namespace = this.$props.namespace;
      return this.$store.state[namespace].loading;
    },
    columnsData: function () {
      let columns = this.columns;
      if (!columns) {
        columns = [];
      }
      let newColumns = [];
      for (let i = 0; i < columns.length; i++) {
        if (appService.hasPermission(columns[i].permissions)) {
          if (appService.hasRole(columns[i].roles)) {
            newColumns.push(columns[i]);
          }
        }
      }
      return newColumns;
    }
  },
  methods: {
    /** 表格行颜色标注 */
    rowClassName(row, index) {
      if (this.$props.namespace === 'settlementDetail' && row.reconciliation_status != 'success') {
        return 'demo-table-info-row';
      }
    },
    handlePageChange(currentPage) {
      let data = {
        currentPage: currentPage
      }
      this.$store.dispatch(`${this.$props.namespace}/query`, data);
    },
    /** 切换每页条数的回调 **/
    handlePageSizeChange(size) {
      let data = {
        pageSize: size
      }
      this.$store.dispatch(`${this.$props.namespace}/query`, data);
    },
    handleSelectChange(selection) {
      let selectedRows = this.selectedRows;
      //老选择项id与老选择项的映射
      let olgSelectedMap = {};
      for (let i = 0; i < selectedRows.length; i++) {
        let selectedRow = selectedRows[i];
        if (!(selectedRow instanceof Object)) {
          let temp = {};
          temp[this.primaryKey] = selectedRow;
          selectedRow = temp;
        }
        olgSelectedMap[selectedRow[this.primaryKey]] = selectedRow;
      }
      //新选择项id与新选择项的映射
      let newSelectedMap = {};
      for (let i = 0; i < selection.length; i++) {
        newSelectedMap[selection[i][this.primaryKey]] = selection[i];
      }
      //获取取消选择项目
      let cancelSelect = [];
      for (let key in olgSelectedMap) {
        if (!newSelectedMap[key]) {
          cancelSelect.push(olgSelectedMap[key]);
        }
      }
      //获取新增选择项目
      let addSelect = [];
      for (let key in newSelectedMap) {
        if (!olgSelectedMap[key]) {
          addSelect.push(newSelectedMap[key]);
        }
      }
      this.$emit("on-selection-change", selection, addSelect, cancelSelect);
      this.$emit("onSelectionChange", selection, addSelect, cancelSelect);
    },
    handleSortChange(sort) {
      this.$emit("onSortChange", sort);
    },
    /** 加载数据 */
    loadData() {
      if (this.needQueryParam && !this.queryParam) {
        return;
      }
      if (this.$props.namespace) {
        this.$store.commit(`${this.$props.namespace}/saveState`, {
          pageInfo: {
            list: [],
            pagination: {}
          }
        });
        let queryParam = this.$props.queryParam;
        if (!queryParam) {
          queryParam = {};
        }
        if (this.$props.isClearStoreQuery) { // 是否清空store中的query数据
          this.$store.commit(`${this.$props.namespace}/saveState`, {query: {}});
        }
        this.$store.dispatch(`${this.$props.namespace}/query`, queryParam);
      }
    },
    getTables() {
      return this.$refs.tables;
    }
  }
};
</script>

<style lang="less">
.ivu-table .demo-table-info-row td {
  background-color: #fff;
  color: red;
}

.show_count {
  text-align: right;
}

.pro-table {
&__search {
.ivu-card-body {
  padding-bottom: 0;
}
}
&__body {
   margin-top: 16px;
.ivu-card-extra + .ivu-card-body {
  margin-top: 46px;
}
}
&__page {
   margin-top: 10px;
   text-align: right;
 }
}
</style>
